// models/Comment.js
const mongoose = require('mongoose');

const commentSchema = new mongoose.Schema({
    discussionId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Discussion',
        required: true
    },
    authorId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    content: {
        type: String,
        required: true,
        maxlength: 1000
    },
    parentCommentId: {  // 支持回复评论
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Comment',
        default: null
    },
    likes: {
        type: Number,
        default: 0
    },
    replyCount: {
        type: Number,
        default: 0
    },
    status: {
        type: String,
        enum: ['active', 'deleted'],
        default: 'active'
    }
}, {
    timestamps: true
});

// 静态方法：获取讨论的评论数量
commentSchema.statics.getCommentCount = function(discussionId) {
  return this.countDocuments({ 
    discussionId, 
    parentCommentId: null, // 只统计顶级评论
    status: 'active' 
  });
};

// 实例方法：检查用户是否可以删除评论
commentSchema.methods.canDelete = function(userId) {
  return this.authorId.toString() === userId;
};

const Comment = mongoose.model('Comment', commentSchema);
module.exports = Comment;